import React, { useEffect, useState, useRef } from 'react';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';

import s from './login.module.less';

function Login() {
  const ref: React.RefObject<any> = useRef();
  const [img, setImg] = useState<string>();
  const [uuid, setUuid] = useState<string>();
  const [username, setUsername] = useState<string>();
  const [password, setPassword] = useState<string>();
  const [code, setCode] = useState<string>();
  const navigate = useNavigate();

  useEffect(() => {
    getCaptcha();
  }, []);

  // 获取验证码
  const getCaptcha = () => {
    $get('/captchaImage').then(res => {
      if (res.code === 200) {
        setImg(`data:image/png;base64,${res.img}`);
        setUuid(res.uuid);
      }
    });
  };

  // 提交事件
  const onSubmit = () => {
    $post('/login', { username, password, uuid: uuid, code }).then(res => {
      if (res.code === 200) {
        localStorage.setItem('token', res.token);
        message.success('登录成功,跳转中...');
        setTimeout(() => {
          navigate('/');
        }, 500);
      } else {
        message.error(`登录失败,${res.msg}`);
        getCaptcha();
      }
    });
  };

  // 表单change事件
  const onchaged = (key: string) => {
    return (e: { target: { value: React.SetStateAction<string | undefined> } }) => {
      switch (key) {
        case 'username':
          setUsername(e.target.value);
          break;
        case 'password':
          setPassword(e.target.value);
          break;
        case 'code':
          setCode(e.target.value);
          break;
        default:
          break;
      }
    };
  };

  return (
    <div className={s['bg']}>
      <div className={s['login']}>
        <h1>MAGIC</h1>
        <form ref={ref}>
          <input
            onChange={onchaged('username')}
            type="text"
            maxLength={18}
            name="username"
            autoComplete="off"
            placeholder="用户名"
            required
          />
          <input
            onChange={onchaged('password')}
            type="password"
            maxLength={18}
            name="password"
            autoComplete="off"
            placeholder="密  码"
            required
          />
          <div className={s.captcha}>
            <input
              onChange={onchaged('code')}
              type="text"
              maxLength={10}
              name="code"
              autoComplete="off"
              required
              placeholder="验证码"
            />
            <img src={img} onClick={getCaptcha} />
          </div>
          <button type="button" onClick={onSubmit}>
            登录
          </button>
        </form>
      </div>
    </div>
  );
}

export default Login;
